package com.javaclimb.music.controller;

import com.alibaba.fastjson.JSONObject;
import com.javaclimb.music.domain.Collect;
import com.javaclimb.music.service.CollectService;
import com.javaclimb.music.utils.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 收藏控制类
 * */
@RestController
@RequestMapping("/collect")
public class CollectController {

    @Autowired
    private CollectService collectService;

    /**
     * 添加收藏
     * */
    @PostMapping("/add")
    public Object addCollect(Collect collect){
        System.out.println("add collect:" + collect);
        JSONObject jsonObject = new JSONObject();
        if(collect.getSongId() == null || collect.getSongId().equals("")){
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, "收藏歌曲为空");
            return jsonObject;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId", collect.getUserId());
        map.put("songId", collect.getSongId());
        if(collectService.existSongId(map)){
            jsonObject.put(Consts.CODE, 2);
            jsonObject.put(Consts.MSG, "已收藏");
            return jsonObject;
        }
        boolean flag = collectService.insert(collect);
        if(flag){
            jsonObject.put(Consts.CODE, 1);
            jsonObject.put(Consts.MSG, "收藏成功");
            return jsonObject;
        }
        jsonObject.put(Consts.CODE, 0);
        jsonObject.put(Consts.MSG, "收藏失败");
        return jsonObject;
    }

    /**
     * 删除收藏
     * */
    @GetMapping("/delete")
    public Object deleteCollect(Integer userId, Integer songId){
        //return collect;
        Map<String, Integer> map = new HashMap<>();
        map.put("userId", userId);
        map.put("songId", songId);
        boolean flag = collectService.delete(map);
        return flag;
    }


    /**
     * 查询所有收藏
     * */
    @GetMapping("/allCollect")
    public Object selectAllCollect(){
        //return collect;
        return collectService.allCollect();
    }

    /**
     * 查询某个用户下的所有收藏
     * */
    @GetMapping("/collectOfUserId")
    public Object collectOfUserId(Integer userId){
        return collectService.collectOfUserId(userId);
    }

    /**
     * 查询某个用户是否已经收藏了该歌曲
     * */
    @GetMapping("/existSongId")
    public Object existSongId(Integer userId, Integer songId){
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("songId", songId);
        return collectService.existSongId(map);
    }

}
